import { Component, useEffect, useState } from 'react'
import { View, Text, Input, Icon, Swiper, SwiperItem, Image, Button } from '@tarojs/components'
import './index.less'
import Taro from '@tarojs/taro'
import { connect } from 'react-redux'
import { getBlogByTitle } from '../../api/blog'

export default function Search(props) {
  const [search, setSearch] = useState('')
  const [list, setList] = useState([])
  const [helpList,setHelpList] = useState([])
  useEffect(() => {
    setSearch(props.search)
  }, [])
  useEffect(() => {
    setSearch(props.detail)
    searchChange(props.detail)
  }, [props.detail])
  
  const Search = (title) => {
    getBlogByTitle(title?title:search)
      .then(res => {
        setList(res.data.data)
      })
  }

  const searchChange = (value) => {
    getBlogByTitle(value)
      .then(res => {
        setHelpList(res.data.data)
        setList([])
      })
  }
  return (
    <View className='searchBox' style={props.searching ? { display: 'block' } : { display: 'none' }}>
      <View className='search searchPage' onClick={search}>
        <Icon class="icon-small" type="search" size="18" color="black"></Icon>
        <Input type='text' name='search' value={search} focus={true} onInput={e => {
          setSearch(e.detail.value)
          searchChange(e.detail.value)
          /* props.searchChange(e.detail.value) 搜索内容同步到home*/
        }} onConfirm={Search}/>
        <Icon class="icon-small" type="clear" size="18" color="#999" onClick={()=>{
          setSearch([])
          setList([])
          setHelpList([])
        }}></Icon>
      </View>
      <Text onClick={props.check} className="button">取消</Text>
      {/* <View className="button">
        <Button onClick={Search}>搜索</Button>
        <Button onClick={props.check}>取消</Button>
      </View> */}
      {
        list.length?
        list.map(item => (
          <View style={{ border: '1px solid black' }} onClick={() => { Taro.navigateTo({ url: '/pages/detail/index?blog_id=' + item.blog_id }) }}>
            <View>标题：{item.title}</View>
            <View>内容：{item.content}</View>
            <View>作者：{item.user_data ? item.user_data[0].nickname : ''}</View>
            <View>发布时间：{item.time}</View>
          </View>
        )):
        helpList.map(item => (
          <View style={{ border: '1px solid black' }} onClick={() => { 
            Search(item.title)
            setSearch(item.title)  
          }}>
            <View>标题：{item.title}</View>
          </View>
        ))
      }
    </View>
  )
}
